<template>
  <div class="wrap padding-b">
    <el-form label-position="top" :rules="rules" ref="form" :model="form" class="form-width" style="padding: 0">
      <div class="b-select-flex" :class="link === 'webchat' ? 'b-select-row' : ''">
        <el-form-item
          :label="label"
          :prop="'value' + n"
          v-for="(one, n) in cascade"
          :key="n"
          :class="n ? 'select-norequire' : ''"
          class="width-full"
        >
          <m7Select
            class="el-select"
            :placeholder="placeholder || $t('public.pleasePick')"
            filterable
            :options="sub['subordinate' + n]"
            v-model.trim="form['value' + n]"
            :type="'business'"
            @input="change($event, n, true)"
          ></m7Select>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
import { getDicOptionsById } from '@/utils/m7Utils.js'
import { getDicFromField } from '@/utils/workflowUtils'
import m7Select from '@components/ui-modules/select/select.vue'
export default {
  name: 'BSelect',
  components: { m7Select },
  props: {
    label: String,
    default: { type: Array },
    id: String,
    dic: '',
    disabled: { type: String | Boolean, default: false },
    placeholder: { type: String, default: '' },
    require: String,
    showOut: '',
    random: { type: Number, default: 0 },
    field: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      sub: {
        subordinate0: [],
        subordinate1: [],
        subordinate2: [],
        subordinate3: [],
        subordinate4: []
      },
      options: {},
      form: {
        value0: this.default[0] || '',
        value1: this.default[1] || '',
        value2: this.default[2] || '',
        value3: this.default[3] || '',
        value4: this.default[4] || ''
      },
      cascade: 1,
      rules: {
        value0: [{ message: this.$t('validate.required'), required: this.require === 'required', trigger: 'change' }],
        value1: [{ message: this.$t('validate.required'), required: this.require === 'required', trigger: 'change' }],
        value2: [{ message: this.$t('validate.required'), required: this.require === 'required', trigger: 'change' }],
        value3: [{ message: this.$t('validate.required'), required: this.require === 'required', trigger: 'change' }],
        value4: [{ message: this.$t('validate.required'), required: this.require === 'required', trigger: 'change' }]
      }
    }
  },
  inject: {
    link: { default: '' }
  },
  methods: {
    change(key, n, flag, isAuto) {
      if (!key) {
        // 从一级开始选子级清空
        if (flag) {
          for (let i = n; i < this.cascade - 1; i++) {
            this.form['value' + (i + 1)] = ''
            this.sub['subordinate' + (i + 1)] = []
          }
        }
        // 主动赋值时不执行
        if (!isAuto || this.form.value0 == '') {
          // 当第一项没有数据时都展示所有数据项
          // 当父级有值时自己展示父级下的数据
          if (this.form['value' + (n - 1)]) {
            return
          } else {
            // 若没有展示全部数据
            this.sub.subordinate0 = []
            this.sub.subordinate1 = []
            this.sub.subordinate2 = []
            this.sub.subordinate3 = []
            this.sub.subordinate4 = []
            this.options = getDicFromField(this.field, this.$getCache('custTmpls'), this.$getCache('options')) || {
              options: []
            }
            this.cascade = parseInt(this.options.cascade) || 1
            if (this.options.options) {
              this.sub.subordinate0 = this.options.options
              let a = 0
              this.filterList(this.options.options, a)
            }
          }
        }
      }
      // 重置 从一往后
      if (key && n !== 4) {
        if (flag) {
          for (let i = n; i < this.cascade - 1; i++) {
            this.form['value' + (i + 1)] = ''
            this.sub['subordinate' + (i + 1)] = []
          }
          let childOptions = getDicOptionsById(key, this.sub['subordinate' + n]) || []
          this.sub['subordinate' + (n + 1)] = []
          this.sub['subordinate' + (n + 1)] = childOptions
          this.addValidateSelect(childOptions, n, this.cascade)
        }
      }
      // // 从后往前
      if (key && n > 0) {
        this.sub['subordinate' + (n - 1)].forEach((item) => {
          if (item.options) {
            item.options.forEach((val) => {
              if (val.key === key) {
                this.form['value' + (n - 1)] = item.key || ''
                this.change(item.key, n - 1, false)
              }
            })
          }
        })
        for (let i = 0; i < this.cascade - 1; i++) {
          let childOptions = getDicOptionsById(this.form['value' + i], this.sub['subordinate' + i]) || []
          this.sub['subordinate' + (i + 1)] = []
          this.sub['subordinate' + (i + 1)] = childOptions
          this.addValidateSelect(childOptions, i, this.cascade)
        }
      }
      // 失去焦点emit数据，工单缓存使用
      // 主动赋值时不缓存
      if (!isAuto) {
        this.$emit('blurEvent', this.submit(true))
      }
    },
    /**
     * @param childOptions 子集的数据
     * @param index 当前触发change事件的Select
     * @param cascade 当前组件是几级级联
     */
    addValidateSelect(childOptions, index, cascade) {
      const len = childOptions.length
      if (len === 0 && cascade > 1) {
        // 子集没有，内容不校验
        for (let i = index + 1; i < cascade; i++) {
          const key = 'value' + i
          this.rules[key][0].required = false
          console.log(this.rules[key])
        }
      } else if (len !== 0 && cascade > 1) {
        for (let i = index + 1; i < cascade; i++) {
          const key = 'value' + i
          if (this.noValidateInDistrict(i)) {
            this.rules[key][0].required = false
          } else {
            this.rules[key][0].required = this.require === 'required'
          }
          console.log(this.rules[key])
        }
      }
    },
    // 字段为省市县，县这个字段不校验
    noValidateInDistrict(i) {
      // requireType为几，则前几级必填
      if (this.field.requireType && i > this.field.requireType - 1) {
        return true
      }
      if (this.options.name === '省市县' && this.options.accountId === 'system' && i === 2) {
        return true
      }
    },
    submit(noCheck) {
      // noCheck为true 不进行校验
      let obj = {}
      if (noCheck) {
        obj.success = true
      } else {
        this.$refs.form.validate((valid) => {
          obj.success = valid
        })
      }
      if (obj.success) {
        obj.data = {}
        for (let index = 0; index < this.cascade; index++) {
          let num = index.toString()
          let value = this.form['value' + num] || ''
          if (!index) {
            obj.data[this.id] = value
          } else {
            obj.data[this.id + '_' + index] = value
          }
        }
      }
      return obj
    },
    filterMenuList(list, index) {
      if (list) {
        if (list.options) {
          list.options.forEach((item) => {
            this.sub['subordinate' + (index + 1)].push(...item.options)
            this.filterMenuList(this.sub['subordinate' + (index + 1)], index + 1)
          })
        }
      }
    },
    filterList(list, index) {
      if (index < this.cascade - 1) {
        if (list) {
          list.forEach((item) => {
            if (item.options) {
              this.sub['subordinate' + (index + 1)].push(...item.options)
              this.filterList(item.options, index + 1)
            }
          })
        }
      }
    }
  },
  computed: {},
  watch: {},
  beforeMount() {
    this.options = getDicFromField(this.field, this.$getCache('custTmpls'), this.$getCache('options')) || {
      options: []
    }
    this.cascade = parseInt(this.options.cascade) || 1
    if (this.options.options) {
      this.sub.subordinate0 = this.options.options
      this.filterMenuList(this.options.options, 1) //递归获取
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.form.value0 = ''
      this.options.options.some((item) => {
        if (this.default[0] && item.key === this.default[0]) {
          this.form.value0 = this.default[0] || ''
          return true
        }
      })
      Object.keys(this.rules).forEach((item, index) => {
        this.rules[item][0].required = !this.noValidateInDistrict(index) && this.require === 'required'
      })
      if (this.cascade > 1) {
        this.change(this.default[0], 0, true, true)
        this.form.value1 = this.default[1] || ''
      }
      if (this.cascade > 2) {
        this.change(this.default[1], 1, true, true)
        this.form.value2 = this.default[2] || ''
      }
      if (this.cascade > 3) {
        this.change(this.default[2], 2, true, true)
        this.form.value3 = this.default[3] || ''
      }
      if (this.cascade > 4) {
        this.change(this.default[3], 3, true, true)
        this.form.value4 = this.default[4] || ''
      }
    })
  }
}
</script>
<style lang="stylus">
@import "../base.styl"
</style>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl";
.padding-b
  padding-bottom 8px
.width-full
  width 100%
.form-width
  width 100%
  padding-left 20px
.b-select-flex
  display flex
.b-select-row
  display block
  .select-norequire
    padding-left 0px
</style>
